// scripts/run-with-timeout.js
// Hard-kill any command that exceeds GLOBAL_TIMEOUT_MS (default 60s)
import { spawn } from 'child_process';

const CMD = process.argv.slice(2).join(' ');
// 默认 60 秒。可通过环境变量覆盖：GLOBAL_TIMEOUT_MS=45000 npm run test:ui:ci
const HARD_TIMEOUT_MS = parseInt(process.env.GLOBAL_TIMEOUT_MS || '60000', 10);

console.log(`[Runner] Start: ${CMD}`);
console.log(`[Runner] Hard timeout: ${HARD_TIMEOUT_MS/1000}s`);

const child = spawn(CMD, { shell: true, stdio: 'inherit' });

const timer = setTimeout(() => {
  console.error(`[Runner] TIMEOUT reached -> killing process...`);
  try { process.kill(-child.pid); } catch {}
  try { child.kill('SIGKILL'); } catch {}
}, HARD_TIMEOUT_MS);

child.on('close', (code) => {
  clearTimeout(timer);
  console.log(`[Runner] Exit code: ${code}`);
  process.exit(code ?? 1);
});
